package com.company.indicationshots.activity;

import static com.company.indicationshots.activity.CommSettingActivity.writeParamsAction;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.company.indicationshots.R;
import com.company.indicationshots.adapter.CurrListAdapter;
import com.company.indicationshots.database.DatabaseHelper;
import com.company.indicationshots.model.Score;
import com.company.indicationshots.services.CommServices;
import com.company.indicationshots.util.CenterOfPoints;
import com.company.indicationshots.util.FindZeroIndices;
import com.company.indicationshots.util.HexToBinaryConverter;
import com.company.indicationshots.util.RightTriangleAngleCalculator;
import com.company.indicationshots.util.VarianceCalculator;
import com.company.indicationshots.view.CurrCoordinateSystemView;
import com.company.indicationshots.view.StrokeTextView;
import com.company.indicationshots.view.PreShotTargetResultView;
import com.target.communication.service.CommSer;
import com.target.communication.service.ICommData;
import com.target.communication.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

//主页面，当前射靶页面
public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";
    private static final Pattern HEX_PATTERN = Pattern.compile("^[0-9A-Fa-f]+$");
    int currNum = 0;
    float currRing = 0;
    float currSum = 0;
    float currAvg = 0;
    String distance = null;
    List<Float> ringList = new ArrayList<>();
    CurrCoordinateSystemView currListChart;
    List<Score> coordList = new ArrayList<>();
    List<Map<String, Object>> targetScoreList = new ArrayList<>();
    List<Score> scoreList = new ArrayList<>();
    float ring;
    String pos;
    float time;
    CurrListAdapter currListAdapter;
    MediaPlayer mediaPlayer;
    int shot = 1;
    int locationReport = 1;
    String gunType = "95式自动步枪";
    int gunData = 1;
    DatabaseHelper dbHelper = new DatabaseHelper(this);
    String[] from = {"curr_list_num", "curr_list_ring", "curr_list_position", "curr_list_distance", "curr_list_time"};
    int[] to = {R.id.curr_list_num, R.id.curr_list_ring, R.id.curr_list_position, R.id.curr_list_distance, R.id.curr_list_time};
    List<Date> dateList = new ArrayList<>();
    private String serialPortPath = null;
    private Integer baudRate = null;
    public CommSer commBinder;
    StrokeTextView shootTitle;
    ListView currList;
    String targetData;
    boolean open;
    Date dataMs = null;
    String shooter;
    //子弹数量
    int bulletCount = 30;
    public static String mode;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onBindingDied(ComponentName name) {
            ServiceConnection.super.onBindingDied(name);
        }

        //Activity与Service断开连接时回调该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "main onServiceDisconnected");
        }

        //Activity与Service连接成功时回调该方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "main onServiceConnected");
            commBinder = (CommSer) service;
            try {
                commBinder.setSerialPortPath(serialPortPath);
                commBinder.setBaudRate(baudRate);
                openSerial();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            commBinder.setiDataSerial(new ICommData() {

                @Override
                public void dataCallBack(byte[] var1) {
                    //接收数据
                    String receiveData = StringUtil.bytesToHex(var1);
                    //当前射靶
                    currShot(receiveData);
                }
            });
        }
    };


    @SuppressLint({"MissingInflatedId", "Range"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //列表list按钮跳转
        ImageView list = findViewById(R.id.list);
        list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SmartIntegrateTargetActivity.class);
                startActivity(intent);
            }
        });

        //设置setting跳转
        ImageView setting = findViewById(R.id.setting);
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService();
                Intent intent = new Intent(MainActivity.this, UserSettingActivity.class);
                startActivity(intent);
            }
        });

        //注册广播接收器
        IntentFilter filter = new IntentFilter(writeParamsAction);
        LocalBroadcastManager.getInstance(this).registerReceiver(writeParamsBroadcastReceiver, filter);

        TextView gunTypeView = findViewById(R.id.gun_type);
        shootTitle = findViewById(R.id.shoot_title);
        TextView save = findViewById(R.id.save);

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String shootDistance = "100";

        String sql = "select name from user where isSelect = 1";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            shooter = cursor.getString(cursor.getColumnIndex("name"));
        }

        sql = "select gunType,bulletCount,gunData,shot,locationReport,shootDistance from funcset order by id desc limit 1";
        cursor = db.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            bulletCount = cursor.getInt(cursor.getColumnIndex("bulletCount"));
            gunType = cursor.getString(cursor.getColumnIndex("gunType"));
            gunData = cursor.getInt(cursor.getColumnIndex("gunData"));
            shot = cursor.getInt(cursor.getColumnIndex("shot"));
            locationReport = cursor.getInt(cursor.getColumnIndex("locationReport"));
            shootDistance = cursor.getInt(cursor.getColumnIndex("shootDistance")) + "";
        }

        TextView shooterView = findViewById(R.id.shooter);
        ImageView riflePic = findViewById(R.id.rifle_pic);
        ImageView pistolPic = findViewById(R.id.pistol_pic);
        CardView saveCard = findViewById(R.id.saveCard);
        if (StrUtil.isNotBlank(shooter)) {
            shooterView.setText("射手 : " + shooter);
        }
        if ("95式自动步枪".equals(gunType)) {
            gunType = "枪型 : 95";
            riflePic.setVisibility(View.VISIBLE);
            pistolPic.setVisibility(View.GONE);
        } else {
            gunType = "枪型 : 92";
            riflePic.setVisibility(View.GONE);
            pistolPic.setVisibility(View.VISIBLE);
        }
        gunTypeView.setText(gunType);
        if (gunData == 0) {
            saveCard.setVisibility(View.VISIBLE);
        } else {
            saveCard.setVisibility(View.GONE);
        }
        shootTitle.setText(shootDistance + "米 固定 胸环靶");

        sql = "select serialPortPath,baudRate from commset";
        cursor = db.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            serialPortPath = cursor.getString(cursor.getColumnIndex("serialPortPath"));
            baudRate = cursor.getInt(cursor.getColumnIndex("baudRate"));
        }
        cursor.close();
        db.close();

        if (StrUtil.isNotBlank(serialPortPath) && baudRate != null) {
            //绑定串口服务
            bindService();
        }

        //成绩列表初始化
        currList = findViewById(R.id.curr_list);
        List<Map<String, Object>> data = new ArrayList<>();
        currListAdapter = new CurrListAdapter(this, data, R.layout.curr_list_item, from, to);
        currList.setAdapter(currListAdapter);

        currListChart = findViewById(R.id.curr_list_chart);
        currListChart.setBulletCount(bulletCount);

        //保存按钮
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存
                save();
                //重置页面
                reset();

                dateList = new ArrayList<>();
            }
        });

    }

    //当前射靶
    public void currShot(String receiveData) {

        //最新成绩初始化
        TextView currNumView = findViewById(R.id.curr_num);
        TextView currRingView = findViewById(R.id.curr_ring);
        TextView currSumView = findViewById(R.id.curr_sum);
        TextView currAvgView = findViewById(R.id.curr_avg);
        ImageView currTarget = findViewById(R.id.curr_target);
        shootTitle = findViewById(R.id.shoot_title);
        currList = findViewById(R.id.curr_list);
        //胸环靶的宽和高
        int width = 1901;
        int height = 1901;

        // 计算每个格子的宽度和高度
        float gridWidth = (float) width / 24;
        float gridHeight = (float) height / 24;

        //计算最高环数坐标
        float highestX = (float) width / 2 - 45;
        float highestY = (float) height / 2 + 143;

        //计算环数半径
        float radius = (float) width / (10 * 10);

        //启动串口线程
        String info;
        String wOps;
        String hOps;
        float x;
        float y;
        float dis;
        float num;
        Date preDate;
        Date curDate;
        int size;
        //获取射击距离
        distance = shootTitle.getText().toString();
        distance = distance.substring(0, distance.indexOf("米") + 1);

        //不要枪数据
        if (gunData == 0) {
            //在收到靶数据之后收到枪数据，直接返回
            if (StrUtil.isNotBlank(targetData) && "0100".equals(receiveData)) {
                targetData = null;
                dataMs = null;
                return;
            }
            //单收枪数据直接返回
            if ("0102".equals(receiveData) || "0101".equals(receiveData) || "0100".equals(receiveData)) {
                targetData = null;
                dataMs = null;
                return;
            }
        }

        //要枪数据
        if (gunData == 1) {
            //把射靶接收到的靶数据暂存在targetData中
            if (receiveData.startsWith("1100") && receiveData.endsWith("0000") && receiveData.length() == 20
                    && (HEX_PATTERN.matcher(receiveData.substring(4, 16)).matches())) {
                targetData = receiveData;
                dataMs = new Date();
                return;
            }
        } else {
            //不要枪数据，把射靶接收到的靶数据赋值给targetData，把接收到的靶数据赋值为0100
            if (receiveData.startsWith("1100") && receiveData.endsWith("0000") && receiveData.length() == 20
                    && (HEX_PATTERN.matcher(receiveData.substring(4, 16)).matches())) {
                targetData = receiveData;
                receiveData = "0100";
                dataMs = null;
            }
        }

        //要枪数据且没接收靶数据
        if (gunData == 1 && StrUtil.isBlank(targetData)) {
            //上电
            if ("0102".equals(receiveData)) {
                //播放音频
                if (shot == 1) {
                    int readyAudioId = R.raw.ready;
                    play(readyAudioId);
                }

            }

            //拉栓
            if ("0101".equals(receiveData)) {
                if (shot == 1) {
                    int gunLoadedAudioId = R.raw.loaded;
                    play(gunLoadedAudioId);
                }

                //保存
                save();
                //重置页面
                reset();

                dateList.add(new Date());

            }

            //脱靶
            if ("0100".equals(receiveData)) {
                if (shot == 1) {
                    int missAudioId = R.raw.miss;
                    play(missAudioId);
                }

                //发序加1
                currNum++;
                //当发序大于子弹数量，直接返回
                if (currNum > bulletCount) {
                    currNum = bulletCount;
                    dataMs = null;
                    return;
                }
                //坐标系
                Score score = new Score(currNum, 0, null, null, 0, 0, 0);
                coordList.add(score);

                //计算平均环数
                float result = currSum / currNum;
                currAvg = (float) Math.round(result * 10) / 10;

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        currNumView.setText("发序:" + currNum);
                        currRingView.setText("环数:" + 0.0);
                        currAvgView.setText("平均:" + currAvg);
                        currListChart.setData(coordList);
                    }
                });

                //记录总数据
                score = new Score(currNum, 0, null, distance, 0, 0, time);
                scoreList.add(score);

                dateList.add(new Date());

            }
        }

        //有效环数，接收到靶数据，且接收的枪数据为0100
        if (StrUtil.isNotBlank(targetData) && "0100".equals(receiveData)) {

            //计算枪数据和靶数据时间间隔，大于300ms，这组枪靶数据就不要，丢弃
            if (dataMs != null) {
                long msDiff = DateUtil.betweenMs(dataMs, new Date());
                if (msDiff > 300) {
                    dataMs = null;
                    targetData = null;
                    return;
                }
            }

            //接收的靶数据赋值给receiveData
            receiveData = targetData;
            //发序加1
            currNum++;
            //当发序大于子弹数量，直接返回
            if (currNum > bulletCount) {
                currNum = bulletCount;
                targetData = null;
                dataMs = null;
                return;
            }

            if (shot == 1) {
                int shootAudioId = R.raw.shoot_target;
                play(shootAudioId);
            }

            dateList.add(new Date());
            size = dateList.size();
            //计算每一次射靶所耗时间
            if (size > 1) {
                preDate = dateList.get(size - 2);
                curDate = dateList.get(size - 1);
                long ms = DateUtil.between(preDate, curDate, DateUnit.MS, false);
                double second = (double) ms / 1000.0;
                time = (float) (Math.round(second * 10.0) / 10.0);
            } else {
                time = 0;
            }

            //获取靶数据有效部分
            info = receiveData.substring(4, 16);
            //转成二进制字符串
            info = HexToBinaryConverter.hexToBinary(info);

            //计算位置坐标
            //截取字符串前24位为纵向靶数据
            hOps = info.substring(0, 24);
            //截取字符串后24位为横向靶数据
            wOps = info.substring(24);
            //纵向靶数据找出其中所有字符0所在位置返回一个集合，0代表被触发的格子位置，获得纵向触发格子位置集合
            List<Integer> hIndices = FindZeroIndices.zeroIndices(hOps);
            //横向靶数据找出其中所有字符0所在位置返回一个集合，0代表被触发的格子位置，获得横向触发格子位置集合
            List<Integer> wIndices = FindZeroIndices.zeroIndices(wOps);
            float iy;
            float ix;
            Score score;
            List<Score> scList = new ArrayList<>();
            //当两个集合中有一个元素个数大于1时，遍历纵向和横向位置集合
            if (hIndices.size() > 1 || wIndices.size() > 1) {
                for (Integer hIndex : hIndices) {
                    for (Integer wIndex : wIndices) {
                        //计算当前触发格子的纵坐标和横坐标
                        iy = (hIndex - 1) * gridHeight;
                        ix = (wIndex - 1) * gridWidth;
                        score = new Score(0, 0, null, null, ix, iy, 0);
                        scList.add(score);
                    }
                }
                //计算所有被触发坐标点的中心坐标
                Score centerPoint = CenterOfPoints.calculateCenter(scList);
                x = centerPoint.getX();
                y = centerPoint.getY();
            } else {
                //当两个集合都只有一个元素时，直接计算触发点的坐标
                x = (wIndices.get(0) - 1) * gridWidth;
                y = (hIndices.get(0) - 1) * gridHeight;
            }

            //计算环数,计算触发点的坐标和最高环，也就是靶10环中心，之间的距离
            dis = (float) Math.sqrt((x - highestX) * (x - highestX) + (y - highestY) * (y - highestY));
            //计算触发点坐标和最高环的环数差
            num = dis / radius;
            //计算当前触发点的环数，保留两位小数
            ring = (float) (Math.round((10.9 - num * 0.1) * 10.0) / 10.0);

            //小于5环，就是脱靶的，直接返回
            if (ring < 5.0) {
                targetData = null;
                dataMs = null;
                return;
            }

            //有位置播报
            if (locationReport == 1) {
                String ringAudio = (ring + "").replaceAll("\\.", "_");
                // 获取raw文件夹下音频文件的资源ID
                int ringAudioId = getResources().getIdentifier("ring_" + ringAudio, "raw", getPackageName());
                play(ringAudioId);
            }

            //判断当前射靶坐标对于最高环的方位情况
            int dirAudioId;
            if (x == highestX && y < highestY) {
                pos = "上";
                if (locationReport == 1) {
                    dirAudioId = R.raw.up;
                    play(dirAudioId);
                }
            }
            if (x == highestX && y > highestY) {
                pos = "下";
                if (locationReport == 1) {
                    dirAudioId = R.raw.down;
                    play(dirAudioId);
                }
            }
            if (y == highestY && x < highestX) {
                pos = "左";
                if (locationReport == 1) {
                    dirAudioId = R.raw.left;
                    play(dirAudioId);
                }
            }
            if (y == highestY && x > highestX) {
                pos = "右";
                if (locationReport == 1) {
                    dirAudioId = R.raw.right;
                    play(dirAudioId);
                }
            }
            if (x == highestX && y == highestY) {
                pos = "";
            }

            //当目前的射靶坐标与最高环的坐标都不相同
            if (x != highestX && y != highestY) {
                //计算x坐标值
                double absX = Math.abs(x - highestX);
                //计算y坐标值
                double absY = Math.abs(y - highestY);
                //计算射靶坐标与中心坐标系y轴的夹角
                double angleXY = RightTriangleAngleCalculator.calculateAngle(absX, absY);

                //当夹角大于22.5度时
                if (angleXY > 22.5) {
                    //计算射靶坐标与中心坐标系x轴的夹角
                    double angleYX = RightTriangleAngleCalculator.calculateAngle(absY, absX);

                    //当夹角小于等于22.5度时
                    if (angleYX <= 22.5) {
                        if (x < highestX) {
                            pos = "左";
                            if (locationReport == 1) {
                                dirAudioId = R.raw.left;
                                play(dirAudioId);
                            }
                        } else {
                            pos = "右";
                            if (locationReport == 1) {
                                dirAudioId = R.raw.right;
                                play(dirAudioId);
                            }
                        }
                    } else {
                        if (x < highestX && y < highestY) {
                            pos = "左上";
                            if (locationReport == 1) {
                                dirAudioId = R.raw.upleft;
                                play(dirAudioId);
                            }
                        }
                        if (x < highestX && y > highestY) {
                            pos = "左下";
                            if (locationReport == 1) {
                                dirAudioId = R.raw.lowleft;
                                play(dirAudioId);
                            }
                        }
                        if (x > highestX && y < highestY) {
                            pos = "右上";
                            if (locationReport == 1) {
                                dirAudioId = R.raw.upright;
                                play(dirAudioId);
                            }
                        }
                        if (x > highestX && y > highestY) {
                            pos = "右下";
                            if (locationReport == 1) {
                                dirAudioId = R.raw.lowright;
                                play(dirAudioId);
                            }
                        }
                    }
                } else {
                    if (y < highestY) {
                        pos = "上";
                        if (locationReport == 1) {
                            dirAudioId = R.raw.up;
                            play(dirAudioId);
                        }
                    } else {
                        pos = "下";
                        if (locationReport == 1) {
                            dirAudioId = R.raw.down;
                            play(dirAudioId);
                        }
                    }
                }
            }

            //有效环数存入有效环数集合
            ringList.add(ring);
            //计算最高环数
            currRing = Collections.max(ringList);
            //计算总环数，四舍五入保留一位小数
            currSum = (float) Math.round((currSum + ring) * 10) / 10;
            //计算平均环数，四舍五入保留一位小数
            float result = currSum / currNum;
            currAvg = (float) Math.round(result * 10) / 10;

            //成绩列表
            Map<String, Object> map = new HashMap<String, Object>() {{
                put("curr_list_num", currNum);
                put("curr_list_ring", ring);
                put("curr_list_position", pos);
                put("curr_list_distance", distance);
                put("curr_list_time", time);
            }};

            //胸环靶
            Map<String, Object> scoreMap = new HashMap<>();
            scoreMap.put("x", x);
            scoreMap.put("y", y);
            targetScoreList.add(scoreMap);

            //坐标系
            score = new Score(currNum, ring, null, null, 0, 0, 0);
            coordList.add(score);

            //更新界面
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    currNumView.setText("发序:" + currNum);
                    currRingView.setText("环数:" + ring);
                    currSumView.setText("总环数:" + currSum);
                    currAvgView.setText("平均:" + currAvg);
                    currListAdapter.addRow(map);
                    //成绩列表定位到最新一行
                    int lastPosition = ringList.size() - 1;
                    if (lastPosition >= 0) {
                        currList.setSelection(lastPosition);
                    }
                    PreShotTargetResultView targetResultView = new PreShotTargetResultView();
                    targetResultView.getTargetView(MainActivity.this, targetScoreList, scoreMap, currTarget);
                    currListChart.setData(coordList);
                }
            });

            //记录总数据
            score = new Score(currNum, ring, pos, distance, x, y, time);
            scoreList.add(score);

            dataMs = null;
            targetData = null;
        }
    }

    //保存
    public void save() {
        TextView shooterView = findViewById(R.id.shooter);
        TextView gunTypeView = findViewById(R.id.gun_type);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (CollUtil.isNotEmpty(ringList)) {
            String shooter = shooterView.getText().toString();
            shooter = shooter.substring(shooter.indexOf(":") + 1).trim();
            String gunType = gunTypeView.getText().toString();
            if (gunType.endsWith("95")) {
                gunType = "95式自动步枪";
            } else {
                gunType = "92式手枪";
            }

            //计算脱靶数，总数减有效环数
            int miss = currNum - ringList.size();

            //计算方差
            float variance = 0f;
            if (CollUtil.isNotEmpty(ringList)) {
                variance = VarianceCalculator.calculateVariance(ringList);
            }
            String createTime = DateUtil.format(DateUtil.date(), "yyyy/MM/dd HH:mm");

            // 开始事务
            db.beginTransaction();
            try {
                //记录表 record
                ContentValues values = new ContentValues();
                values.put("shooter", shooter);
                values.put("gun_type", gunType);
                values.put("sum", currNum);
                values.put("miss", miss);
                values.put("highest", currRing);
                values.put("avg", currAvg);
                values.put("variance", variance);
                values.put("create_time", createTime);
                long recordId = db.insert("record", null, values);

                //成绩表 score
                for (Score score : scoreList) {
                    values.clear();
                    values.put("num", score.getNum());
                    values.put("record_id", recordId);
                    values.put("ring", score.getRing());
                    values.put("position", score.getPosition());
                    values.put("distance", score.getDistance());
                    values.put("x", score.getX());
                    values.put("y", score.getY());
                    values.put("time", score.getTime());
                    values.put("create_time", createTime);
                    db.insert("score", null, values);
                }

                // 如果所有操作都成功，标记事务为成功
                db.setTransactionSuccessful();
            } catch (Exception e) {
                // 处理执行数据库操作时发生的异常
                e.printStackTrace();
                // 发生异常，不调用setTransactionSuccessful()则默认会回滚
            } finally {
                // 结束事务
                // 如果之前调用了setTransactionSuccessful()则提交事务，否则回滚
                db.endTransaction();

                db.close();
            }

        }
    }

    //重置页面
    public void reset() {

        TextView currNumView = findViewById(R.id.curr_num);
        TextView currRingView = findViewById(R.id.curr_ring);
        TextView currSumView = findViewById(R.id.curr_sum);
        TextView currAvgView = findViewById(R.id.curr_avg);
        ListView currList = findViewById(R.id.curr_list);
        ImageView currTarget = findViewById(R.id.curr_target);

        currNum = 0;
        currRing = 0;
        currSum = 0;
        currAvg = 0;
        ringList = new ArrayList<>();
        coordList = new ArrayList<>();
        targetScoreList = new ArrayList<>();
        scoreList = new ArrayList<>();
        time = 0;
        targetData = null;
        dataMs = null;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                currNumView.setText("发序:" + currNum);
                currRingView.setText("环数:" + currRing);
                currSumView.setText("总环数:" + currSum);
                currAvgView.setText("平均:" + currAvg);
                currListAdapter = new CurrListAdapter(MainActivity.this, new ArrayList<>(), R.layout.curr_list_item, from, to);
                currList.setAdapter(currListAdapter);
                currListChart.setData(coordList);
                PreShotTargetResultView targetResultView = new PreShotTargetResultView();
                targetResultView.getTargetView(MainActivity.this, targetScoreList, new HashMap<>(), currTarget);
            }
        });

    }

    //播放音频
    public void play(int audioId) {
        // 创建 MediaPlayer 实例
        mediaPlayer = MediaPlayer.create(MainActivity.this, audioId);
        // 设置播放完成后的监听器，用于释放资源
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release(); // 释放资源
                mediaPlayer = null; // 将mediaPlayer置为null
            }
        });
        // 开始播放音频
        if (mediaPlayer != null) {
            mediaPlayer.start();
        }
    }

    //串口服务
    /*
     *   绑定服务
     * */
    public void bindService() {
        Intent intent = new Intent(this, CommServices.class);
        intent.putExtra("param", "param1");
        Log.i(TAG, "main bindService");
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }

    //解绑服务
    private void unbindService() {
        if (commBinder == null) {
            Log.i(TAG, "main unbindService,binder is null");
            return;
        }
        unbindService(conn);
        commBinder = null;
        Log.i("main unbindService", "main unbindService success");
    }

    //打开串口
    public void openSerial() throws IOException {
        open = commBinder.connSerial();
        Log.i("main openSerial", "main serial open success");
    }

    //关闭串口
    public void closeSerial() throws IOException {
        if (open) {
            commBinder.closeSerial();
            open = false;
            Log.i("closeSerial", "main close serial success");
        } else {
            Log.i("closeSerial", "main close serial is null");
        }
    }

    //广播接收通信设置发送的新设置的串口路径和波特率
    private BroadcastReceiver writeParamsBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 检查Intent的action是否匹配
            if (intent.getAction().equals(writeParamsAction)) {
                serialPortPath = intent.getStringExtra("serialPortPath");
                baudRate = intent.getIntExtra("baudRate", 115200);
            }
        }
    };

    // 在 Activity 销毁时确保释放资源
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop(); // 如果正在播放，先停止
            }
            mediaPlayer.release(); // 释放资源
            mediaPlayer = null; // 将mediaPlayer置为null
        }

        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(writeParamsBroadcastReceiver);

        //关闭串口和解绑
        try {
            closeSerial();
            unbindService();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        reset();

    }

    //接收其他页面的跳转
    @SuppressLint("Range")
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String activity = intent.getStringExtra("activity");

        if ("userSetting".equals(activity)) {
            TextView shooterView = findViewById(R.id.shooter);
            String shooterText = intent.getStringExtra("shooterText");
            if (StrUtil.isBlank(shooterText)) {
                shooterText = "射手 : 未指定";
            }
            shooterView.setText(shooterText);
        }
        if ("funcSetting".equals(activity)) {
            TextView gunTypeView = findViewById(R.id.gun_type);
            StrokeTextView shootTitle = findViewById(R.id.shoot_title);
            ImageView riflePic = findViewById(R.id.rifle_pic);
            ImageView pistolPic = findViewById(R.id.pistol_pic);
            CardView saveCard = findViewById(R.id.saveCard);
            gunData = intent.getIntExtra("gunData", 1);
            gunType = intent.getStringExtra("gunType");
            bulletCount = intent.getIntExtra("bulletCount", 30);
            shot = intent.getIntExtra("shot", 1);
            locationReport = intent.getIntExtra("locationReport", 1);
            int shootDistance = intent.getIntExtra("shootDistance", 100);
            if (gunData == 0) {
                saveCard.setVisibility(View.VISIBLE);
            } else {
                saveCard.setVisibility(View.GONE);
            }
            if ("95式自动步枪".equals(gunType)) {
                gunType = "枪型 : 95";
                riflePic.setVisibility(View.VISIBLE);
                pistolPic.setVisibility(View.GONE);
            } else {
                gunType = "枪型 : 92";
                riflePic.setVisibility(View.GONE);
                pistolPic.setVisibility(View.VISIBLE);
            }
            gunTypeView.setText(gunType);
            shootTitle.setText(shootDistance + "米 固定 胸环靶");
            currListChart.setBulletCount(bulletCount);
        }

        if (StrUtil.isNotBlank(serialPortPath) && baudRate != null) {
            bindService();
        }

    }

}